<?php
namespace DaChongQing\Controller;
use Think\Controller;
use LaneWeChat\Core\WeChatOAuth;
/**
 * Created by PhpStorm.
 * User: medivh
 * Date: 15-6-11
 * Time: 上午9:51
 */
class NewsController extends Controller {
    /**
     * 新闻列表
     */
    public function index(){
        if(cookie('nickname') == null){
            #验证是否存在cookie保存的微信用户信息，不存在执行获取信息操作
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".C('APPID')."&secret=".C('APPSECRET')."&code=".I('code')."&grant_type=authorization_code";
            $arr = json_decode(file_get_contents($url));
            $openid = $arr->openid;
            $access_token = AccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."";
            $userinfo = json_decode(file_get_contents($url));
            //cookie保存用户信息
            cookie('openid',$openid);
            cookie('nickname',$userinfo->nickname == null ? '大渝网友' : $userinfo->nickname);
            cookie('sex',$userinfo->sex == null ? '3' : $userinfo->sex);
            cookie('city',$userinfo->city == null ? '火星' : $userinfo->city);
            cookie('province',$userinfo->province == null ? ' ' : $userinfo->province);
            cookie('headimgurl',$userinfo->headimgurl == null ? '/Public/DaChongQing/images/5194d494d7d0073919.jpg' : $userinfo->headimgurl);
        }
        //变量保存分类id
        $column = array(
            'column' => I('column')
        );
        if(!IS_AJAX){
            //v1.0 读取置顶列表
            $whereTop = array(
                'column' => $column['column'],
                'order' => array('gt',0)
            );
            $order = 'lasttime desc , createtime desc';
            $top = M('news_details')->where($whereTop)->order($order)->select();
            //v1.0 读取正常列表
            $whereDetails = array(
                'column' => $column['column'],
                'order' => array('eq',0)
            );
            $list = M('news_details')->where($whereDetails)->order($order)->limit('0,20 `   ')->select();
//            #读取新闻列表
//            $field = 'tid,max(details_time),max(comment_time)';
//            $OrderStr = 'max(comment_time) desc , max(details_time) desc , details_order desc';
//            //置顶新闻读取
//            $where = array(
//                'details_column' => $column['column'],
//                'details_order' => array('gt',0)
//            );
//            $top = M('news_order')->field($field)->where($where)->order($OrderStr)->group('tid')->select();
//            foreach($top as $k => $v){
//                $details = M('news_details')->where(array('id'=>$top[$k]['tid']))->find();
//                $top[$k]['id'] = $details['id'];
//                $top[$k]['thumb'] = $details['thumb'];
//                $top[$k]['title'] = $details['title'];
//                $top[$k]['label'] = $details['label'];
//                $top[$k]['see'] = dig($details['see']);
//                $top[$k]['time'] = $top[$k]['max(details_time)'] > $top[$k]['max(comment_time)'] ? $top[$k]['max(details_time)'] : $top[$k]['max(comment_time)'];
//            }
//            //正常列表
//            $where = array(
//                'details_column' => $column['column'],
//                'details_order' => array('eq',0)
//            );
//            $order = M('news_order')->field($field)->where($where)->order($OrderStr)->group('tid')->limit('0,20')->select();
//            foreach($order as $k => $v){
//                $details = M('news_details')->where(array('id'=>$order[$k]['tid']))->find();
//                $order[$k]['id'] = $details['id'];
//                $order[$k]['thumb'] = $details['thumb'];
//                $order[$k]['title'] = $details['title'];
//                $order[$k]['label'] = $details['label'];
//                $order[$k]['see'] = dig($details['see']);
//                $order[$k]['time'] = $order[$k]['max(details_time)'] > $order[$k]['max(comment_time)'] ? $order[$k]['max(details_time)'] : $order[$k]['max(comment_time)'];
//            }
            $last = M('news_details')->where(array('column'=>$column['column']))->order($order)->limit('1')->find();
            $this->LastTime = $last['lasttime'];
            $this->top = $top;
            $this->list = $list;
//            dump($order);
            $this->display();
        }else{
            #异步加载新闻列表
            $limit = I('limit').',20';
            $where = array(
                'column' => $column['column'],
                'order' => array('eq',0)
            );
            $order = 'lasttime desc , createtime desc';
//            $field = 'tid,max(details_time),max(comment_time)';M('news_details')->where($whereDetails)->order($order)->select();
//            $OrderStr = 'comment_time desc , details_time desc';
            $order = M('news_details')->where($where)->order($order)->limit($limit)->select();
//            foreach($order as $k => $v){
//                $details = M('news_details')->where(array('id'=>$order[$k]['tid']))->find();
//                $order[$k]['id'] = $details['id'];
//                $order[$k]['thumb'] = $details['thumb'];
//                $order[$k]['title'] = $details['title'];
//                $order[$k]['label'] = $details['label'];
//                $order[$k]['see'] = dig($details['see']);
//                $order[$k]['time'] = $order[$k]['max(details_time)'] > $order[$k]['max(comment_time)'] ? $order[$k]['max(details_time)'] : $order[$k]['max(comment_time)'];
//            }
            $this->ajaxReturn(json_encode($order));
        }
    }

    /**
     * 新闻内容
     */
    public function content(){
        if(!IS_AJAX){
    //        self::GetCode();
            $id = I('id');
            $this->details = M('news_details')->where(array('id'=>$id))->find();
            $this->content = M('news_content')->where(array('tid'=>$id))->find();
            $toupiao = M('news_vote')->where(array('tid'=>$id))->select();
            $this->toupiao = $toupiao;
            foreach($toupiao as $k => $v){
                $support[] = $v['support'];
            }
            $this->count = array_sum($support);
            M('news_details')->where(array('id'=>$id))->setInc('see');
            $last = M('news_details')->where(array('id'=>$id))->find();
            $this->LastTime = $last['lasttime'];
            $this->comment = M('news_comment')->where(array('tid'=>$id))->order('createtime desc')->limit('0,20')->select();
            $this->bestc = M('news_comment')->where(array('tid'=>$id))->order('up desc,down desc')->limit('0,3')->select();
            $this->display();
        }else{
            $id = I('id');
            $limit = I('limit').',20';
            $comment = M('news_comment')->where(array('tid'=>$id))->order('createtime desc')->limit($limit)->select();
            $tpl = '';
            foreach ($comment as $key){
                $tpl .= "
                        <li>
                                <div class='col-xs-2'>
                                    <img src=".$key['userimg']." alt='' title='' class='img-circle head'>
                                </div>
                                <div class='col-xs-10'>
                                    <label style='margin-right:15px'>".strCut($key['nickname'],20)."</label>
                                    <span class='' style='float: right;color:#AAA'>来自".$key['province']."</span>
                                    ".self::reply($key['reply'])."
                                    <p class='user-content'>".$key['content']."</p>
                                </div>
                                <div class='col-xs-12'>
                                    <span class='' style='color:#AAA'>".timeFormat($key['createtime'])."</span>
                                    <span class='right math-right'>".$key['up']."</span>
                                    <button data-type='up' data-id=".$key['id']."  class='click-up glyphicon glyphicon-thumbs-up right up btn-reply' style=".$color = $key['id'] == 1 ? 'color:red' : 'color:#333' ." aria-hidden='true'></button>
                                    <button class='right click-reply btn-reply' data-toggle='modal' data-reply=".$key['id']." data-target='#replay'>回复</button>
                                    <button  data-toggle='modal' data-target='#replay' data-type='up' data-reply=".$key['id']."  class='btn-reply click-reply glyphicon glyphicon-comment right up' style='margin-right: 2px;' aria-hidden='true'></button>
                                </div>
                            </li>
                        ";
            }
            $this->ajaxReturn($tpl,'EVAL');
        }
    }
    /**
     * 新闻内容添加与新闻表达处理
     */
    public function publish(){
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
        if(IS_POST){
            $upload = new \Think\Upload();
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath  = './Uploads/';
            $upload->savePath  = '/news/';
            $info = $upload->upload();
            if(!$info) {
                $this->error($upload->getError());
            }else{
                foreach($info as $file){
                    $thumb = '/Uploads/'.$file['savepath'].$file['savename'];
                }
            }
            $image = new \Think\Image();
            $image->open('.'.$thumb);
            $image->thumb(120, 120,\Think\Image::IMAGE_THUMB_FIXED)->save('.'.$thumb);
            $details = array(
                'title' => I('title'),
                'details' => I('details'),
                'label' => I('biaoqian'),
                'column' => I('column'),
                'thumb' => $thumb,
                'createtime' => time(),
                'lasttime' => time(),
                'up' => '0',
                'down' => '0'
            );
            $details_id = M('news_details')->data($details)->add();
//            $order = array(
//                'tid' => $details_id,
//                'details_column' =>$details['column'],
//                'details_time' =>time(),
//                'comment_time' => time()
//            );
            UeditorImageUploadCom(I('content','',''));
            $content = array(
                'tid' => $details_id,
                'content' => I('content','',''),
                'votename' => I('vote_title')
            );
            M('news_content')->data($content)->add();
            foreach(I('toupiao') as $key => $val){
                $tp_arr[] = array(
                    'tid' => $details_id,
                    'vote' => $val,
                    'support' => '0'
                );
            }
            M('news_vote')->addAll($tp_arr);
            M('news_count')->where(array('id'=>1))->save(array('time'=>time()));
//            M('news_order')->add($order);
            $this->success('提交成功，即将返回......',U('News/NewsList'));
        }else{
            $this->column = M('news_column')->select();
            $this->display('add');
        }
    }

    /**
     * 赞这篇文章
     */
    public function up(){
        $id = I('id');
        if(cookie($id) == 1){
            $this->ajaxReturn('1','EVAL');
        }else{
            M('news_details')->where(array('id'=>$id))->setInc('up');
            cookie($id,'1');
        }
//        $id = I('id');
//        M('news_details')->where(array('id'=>$id))->setInc('up');
    }
    /**
     * 踩这篇文章
     */
    public function down(){
        $id = I('id');
        if(cookie($id) == 1){
            $this->ajaxReturn('1','EVAL');
        }else{
            M('news_details')->where(array('id'=>$id))->setInc('down');
            cookie($id,'1');
        }
//        $id = I('id');
//        M('news_details')->where(array('id'=>$id))->setInc('down');
    }
    /**
     * 选择投票执行操作
     */
    public function votePlus(){
        $id = I('id');
        M('news_vote')->where(array('id'=>$id))->setInc('support');
    }
    /**
     * 用户留言写入操作
     */
    public function comment(){
        $id = I('tid');
        $data = array(
            'openid' => cookie('openid'),
            'tid' => I('tid'),
            'userimg' => cookie('headimgurl'),
            'nickname' => cookie('nickname'),
            'province' => cookie('province').cookie('city'),
            'content' => I('content'),
            'up' => 0,
            'down' => 0,
            'reply' => I('reply'),
            'createtime' => time(),
            'replyopenid' => I('replyopenid'),
            'read' => 1,
            'column' => I('column')
        );
        if($data['content'] == null || $data['content'] == ''){
            $this->ajaxReturn('内容不能为空呢');
        }else{
            $result = M('news_comment')->data($data)->add();
            $content = M('news_comment')->where(array('id'=>$result))->find();
            $lastitime = array(
                'lasttime' => time()
            );
            M('news_details')->where(array('id'=>$id))->save($lastitime);
//            $order = array(
//                'tid' => $data['tid'],
//                'details_column' => $data['column'],
//                'details_order' => I('order'),
//                'comment_time' => time()
//            );
//            M('news_order')->data($order)->add();
            $tpl = "
                        <li>
                                <div class='col-xs-2'>
                                    <img src='{$content['userimg']}' alt='' title='' class='img-circle head'>
                                </div>
                                <div class='col-xs-10'>
                                    <label style='margin-right:15px'>".strCut($content['nickname'],26)."</label>
                                    <span class='' style='float: right;color:#AAA'>来自".$content['province']."</span>
                                    ".self::reply($content['reply'])."
                                    <p  class='user-content'>".$content['content']."</p>
                                </div>
                                <div class='col-xs-12'>
                                    <span class='' style='color:#BBB'>".timeFormat($content['createtime'])."</span>
                                    <span class='right math-right'>".$content['up']."</span><span data-type='up' data-id=".$content['id']."  class='click-up glyphicon glyphicon-thumbs-up right up' aria-hidden='true'></span>
                                    <span class='right click-reply' data-toggle='modal' data-reply=".$content['id']." data-reply-openid=".$content['openid']." data-target='#replay'>回复</span><span  data-toggle='modal' data-target='#replay' data-type='up' data-reply=".$content['id']."  data-reply-openid=".$content['openid']."  class='click-reply glyphicon glyphicon-comment right up' style='margin-right: 2px;' aria-hidden='true'></span>
                                </div>
                            </li>
                    ";
            $this->ajaxReturn($tpl,'EVAL');
        }
    }
    /**
     * 赞用户留言
     */
    public function top(){
        $id = I('id');
        if(cookie($id) == 1){
            $this->ajaxReturn('1','EVAL');
        }else{
            $type = I('type');
            if($type == "down"){
                M('news_comment')->where(array('id'=>$id))->setInc('down');
            }else{
                M('news_comment')->where(array('id'=>$id))->setInc('up');
            }
            cookie($id,'1');
        }
    }
    /**
     * 文章后台管理列表
     */
    public function NewsList(){
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
        $id = array(
            'column' => I("id")
        );
        $page = I('page') == '' ? '1' : I('page');
        if($id["column"] == '' || $id["column"] == 0){
            $this->countpage = M('news_details')->count();
            $this->NewsList = M('news_details')->order('`order` desc , createtime desc')->page($page .',10')->select();
            $this->column = M("news_column")->select();
        }else{
            $this->NewsList = M('news_details')->where($id)->order('`order` desc , createtime desc')->page($page .',10')->select();
            $this->countpage = M('news_details')->where($id)->count();
            $this->column = M("news_column")->select();
            $this->column_id = $id['column'];
        }
        $this->display();
    }
    /**
     * 文章后台管理-删除一篇文章
     */
    public function del(){
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
        $id = I('id');
        M('news_details')->where(array('id'=>$id))->delete();
        M('news_content')->where(array('tid'=>$id))->delete();
        M('news_vote')->where(array('tid'=>$id))->delete();
        M('news_order')->where(array('tid'=>$id))->delete();
        $this->success("删除完成！");
    }
    /**
     * 后台管理密码验证
     */
    public function pass(){
        if(I('result') == 0){
            $this->error('密码输入错误');
        }else{
            $this->success("验证通过");
        }
    }
    /**
     * 文章后台管理-更新文章
     */
    public function upd(){
//        dump(I('post.'));die;
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
        if(!IS_POST){
            $id = I('id');
            $this->news_details = M('news_details')->where(array("id"=>$id))->find();
            $this->column = M('news_column')->select();
            $this->news_content = M('news_content')->where(array("tid"=>$id))->find();
            $this->news_vote = M('news_vote')->where(array("tid"=>$id))->select();
            $this->display();
        }else{
//            dump(I('post.'));die;
            $id = I('id');
                $upload = new \Think\Upload();
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath  = './Uploads/';
                $upload->savePath  = '/news/';
                $info = $upload->upload();
                if(!$info) {
                    $thumb = I("thumba",'','');
//                    $this->error($upload->getError());
                }else{
                    foreach($info as $file){
                        $thumb = '/Uploads/'.$file['savepath'].$file['savename'];
                    }
                }
                $image = new \Think\Image();
                $image->open('.'.$thumb);
                $image->thumb(120, 120,\Think\Image::IMAGE_THUMB_FIXED)->save('.'.$thumb);
                $image->thumb(120, 120,\Think\Image::IMAGE_THUMB_FIXED)->save('.'.$thumb);
            $details = array(
                'title' => I('title'),
                'details' => I('details'),
                'column' => I('column'),
                'label' => I('biaoqian'),
                'lasttime' => time(),
                'thumb' => $thumb,
            );
            M('news_details')->where(array('id'=>$id))->save($details);
            UeditorImageUploadCom(I('content','',''));
            $content = array(
                'content' => I('content','',''),
                'votename' => I('vote_title')
            );
            M('news_content')->where(array('tid'=>$id))->save($content);
            $i = 0;
            $support = I('support');
            foreach(I('toupiao') as $key => $val){
                $tp_arr[] = array(
                    'tid' => $id,
                    'vote' => $val,
                    'support' => $support[$i] == '' || $support[$i] == null ? '0' : $support[$i]
                );
                $i++;
            }
//            dump($tp_arr);die;
            M('news_vote')->where(array('tid'=>$id))->delete();
            M('news_vote')->addAll($tp_arr);
            M('news_count')->where(array('id'=>1))->save(array('time'=>time()));
            $this->success('修改成功，即将返回......',U("News/NewsList"));

        }
    }
    /**
     * 点击投票选项之后进行的数据写入和ajax回执操作
     */
    public function GetSuppor(){
        $id = I('id');
        $vote_id = I('vote_id');
        M('news_vote')->where(array('id'=>$vote_id))->setInc('support');
        $toupiao = M('news_vote')->where(array('tid'=>$id))->select();
        $list = '';
        foreach($toupiao as $k => $v){
            $tp[] = $v['support'];
        }
        $count = array_sum($tp);
        foreach($toupiao as $key){
            if($key['id'] == $vote_id){
                $list .= "
                            <div class='tp-now'>
                            <label>&nbsp;&nbsp;".$key['vote']."</label>
                            <div class='progress'>
                            <div class='progress-bar progress-".RandForProgress()." progress-bar-striped active' role='progressbar' aria-valuenow='20' aria-valuemin='0' aria-valuemax='100' style='max-width:80%;min-width: 15%;width: ".(($key['support']/$count)*100)."%'>
                               &nbsp;<span class='glyphicon glyphicon-ok'></span> ".ceil(($key['support']/$count)*100)."%
                            </div>
                            <div class='people'>
                                ".$key['support']."人
                            </div>
                        </div>
                        </div>
                        ";
            }else{
                $list .= "
                        <div class='tp-now'>
                        <label>&nbsp;&nbsp;".$key['vote']."</label>
                        <div class='progress'>
                            <div class='progress-bar progress-".RandForProgress()." progress-bar-striped active' role='progressbar' aria-valuenow='20' aria-valuemin='0' aria-valuemax='100' style='max-width:80%;min-width: 15%;width: ".(($key['support']/$count)*100)."%'>
                              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".ceil(($key['support']/$count)*100)."%
                            </div>
                            <div class='people'>
                                ".$key['support']."人
                            </div>
                        </div>
                        </div>
                    ";
            }
        }
        $this->ajaxReturn($list,'EVAL');
    }


    /**
     * 获取微信用户的第一步，code
     */
    public function GetCode(){
        require C('PUBLIC').'/Public/LaneWeChat/lanewechat.php';
        $url = 'http://weixin.weirongm.com/DaChongQing/News/index/column/'.I('column');
        $redirect_uri = $url;
        WeChatOAuth::getCode($redirect_uri, $state=1, $scope='snsapi_base');
    }
    public function column(){
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
        if(IS_AJAX){
            $data = array(
                'title' => I('title')
            );
            M('news_column')->data($data)->add();
            $this->ajaxReturn("1");
        }else{
            $this->column = M('news_column')->select();
            $this->display();
        }
    }
    public function DelColumn(){
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
            $data = array(
                'id' => I('id')
            );
            M('news_column')->where(array($data))->delete();
            $this->success("删除完成");
    }
    public function UpdColumn(){
        $isSign = new NewsAdminController();
        $isSign ->IsSignIn();
        $id = array(
            'id' => I('id')
        );
        $data = array(
            'title' => I('title')
        );
        M('news_column')->where($id)->save($data);
        $this->ajaxReturn("1","EVAL");
    }
    public function UpdOrder(){
        $id = array('id'=>I('id'));
        $order = array('order'=>I('order'));
        M('news_details')->where($id)->save($order);
        $this->ajaxReturn('1','EVAL');
    }
    public function reply($id){
        $data = array(
            'id' => $id
        );
        $content = M('news_comment')->where($data)->find();
        $list = '';
        if(count($content) != 0){
                $list = "<div class='replay col-xs-12'>
                                        <label class='replay-name'>".$content['nickname']."</label>
                                        <p class='replay-p1'>
                                        <span class='replay-time'>".timeFormat($content['createtime'])."</span>
                                        <span class='replay-from'><span class='glyphicon glyphicon-map-marker'></span> 来自".$content['province']."</span>
                                        </p>
                                        <p class='replay-content'>".$content['content']."</p>
                                    </div>";
        }
        return $list;
    }
    public function MessageCenter(){
        if(!IS_AJAX){
            $openid = array(
                'replyopenid' => cookie('openid')
            );
            $message = M('news_comment')->where($openid)->order('createtime desc')->limit('0,20')->select();
            M('news_comment')->where($openid)->save(array('read' => 0));
            $this->list = $message;
            $this->display();
        }else{
            $openid = array(
                'replyopenid' => cookie('openid')
            );
            $limit = I('limit').',20';
            $message = M('news_comment')->where($openid)->order('createtime desc')->limit($limit)->select();
            foreach($message as $key => $val){
                $message[$key]['replyc'] = M('news_comment')->where(array('id' => $message[$key]['reply']))->find();
            }
            $this->ajaxReturn(json_encode($message));
        }
    }

    public function read(){
        $openid = array(
            'replyopenid' => cookie('openid'),
            'read' => 1,
        );
        $count = M('news_comment')->where($openid)->count();
        $this->ajaxReturn($count);
    }

    /**
     * @param $arr二维数组
     */
    public function ArrList($arr){
        return $arr;
    }
    public function AccessToken(){
        $access_token = AccessToken();
        echo $access_token;
    }
    public function MessageCenterReply(){
        $data = array(
            'openid' => cookie('openid'),
            'tid' => I('tid'),
            'userimg' => cookie('headimgurl'),
            'nickname' => cookie('nickname'),
            'province' => cookie('province').cookie('city'),
            'content' => trim(I('content')),
            'up' => 0,
            'down' => 0,
            'reply' => I('reply'),
            'createtime' => time(),
            'replyopenid' => I('replyopenid'),
            'read' => 1
        );
        if($data['content'] == null || $data['content'] == ''){
            $this->ajaxReturn('内容不能为空呢');
        }else{
            M('news_comment')->data($data)->add();
        }
    }

    public function GetReply(){
        $id = I('id');
        $content = M('news_comment')->where(array('id'=>$id))->find();
        if(count($content)!=0){
            $this->ajaxReturn($content,'JSON');
        }else{
            return '0';
        }
    }

}